package com.wtx.security.service.impl;

import com.wtx.security.common.RedisConstants;
import com.wtx.security.common.RedisService;
import com.wtx.security.service.SysUserService;
import com.wtx.security.vo.SysUserVO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private RedisService redisService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUserVO getByUsername(String username) {
        return new SysUserVO("1", "郭总", "admin", passwordEncoder.encode("admin123"));
    }

    @Override
    public List<String> getPermissionByUserId(String userId) {
        return Arrays.asList("/test/test", "/test/test3");
    }

    @Override
    public void logout() {
        // 获取 SecurityContextHolder 中的用户 id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        SysUserVO sysUserVO = (SysUserVO) authentication.getPrincipal();
        redisService.getStringRedisTemplate().delete(String.format(RedisConstants.USER_KEY_TEMPLATE,sysUserVO.getId()));
    }
}
